package com.dxlau;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by dxlau on 16/8/30.
 */
@Configurable
@PropertySource("classpath:sysconfig.properties")
@ComponentScan("com.dxlau")
public class AppConfig {

    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);

    @Autowired
    Environment environment;

    @Bean
    public Map<String, String> mapCached(){
        Map<String, String> cache = new HashMap<>();
        cache.put("hello", "world");

        return cache;
    }

    /**
     * spring-for-redis+jedis配置
     */
    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate redisTemplate = null;

        //1.构建Jedis连接器
        JedisConnectionFactory connFactory = null;
        //1.1配置连接池参数
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        connFactory = new JedisConnectionFactory(poolConfig);
        //1.2配置连接信息
        connFactory.setHostName(environment.getProperty("redis.host"));
        connFactory.setPort(environment.getProperty("redis.port", Integer.class));
        connFactory.setPoolConfig(poolConfig);
        connFactory.afterPropertiesSet();

        //2.构建RedisTemplate
        redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(connFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        return redisTemplate;
    }
}
